package com.didi.chameleon.example;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.didi.chameleon.sdk.ICmlInstance;
import com.didi.chameleon.sdk.module.CmlCallback;
import com.didi.chameleon.sdk.module.CmlMethod;
import com.didi.chameleon.sdk.module.CmlModule;
import com.didi.chameleon.sdk.module.CmlParam;

import java.util.HashMap;
import java.util.Map;

@CmlModule(alias = "event")
public class EventModule {

    private Map<String, Map<String, CmlCallback<JSONObject>>> callbackMap = new HashMap<>();

    @CmlMethod(alias = "on")
    public void on(ICmlInstance instance,
                   @CmlParam(name = "key") String key,
                   @CmlParam(name = "id") String id,
                   CmlCallback<JSONObject> callback) {
        Map<String, CmlCallback<JSONObject>> map = callbackMap.get(key);
        if (null == map) {
            map = new HashMap<>();
            callbackMap.put(key, map);
        }
        map.put(id, callback);
    }

    @CmlMethod(alias = "off")
    public void off(ICmlInstance instance,
                    @CmlParam(name = "key") String key,
                    @CmlParam(name = "id") String id) {
        Map<String, CmlCallback<JSONObject>> map = callbackMap.get(key);
        if (null == map) {
            return;
        }
        map.remove(id);
    }

    @CmlMethod(alias = "commit")
    public void commit(ICmlInstance instance,
                       @CmlParam(name = "key") String key,
                       @CmlParam(name = "data") JSONObject data) {
        Map<String, CmlCallback<JSONObject>> map = callbackMap.get(key);
        if (null == map) {
            return;
        }
        for (CmlCallback<JSONObject> callback : map.values()) {
            try {
                callback.onCallback(data);
            } catch (Exception e) {
                Log.d(EventModule.class.getSimpleName(), e.getMessage(), e);
            }
        }
    }
}
